package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.exception.BussinessException;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.entity.SetmealDto;
import com.itheima.reggie.mapper.SetmealMapepr;
import com.itheima.reggie.service.SetMealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapepr, Setmeal> implements SetmealService {
    @Autowired
    private SetMealDishService setMealDishService;

    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //封装普通属性
        this.save(setmealDto);
        //封装菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes=setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setMealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lqw1=new LambdaQueryWrapper<>();
        lqw1.in(Setmeal::getId,ids);
        lqw1.eq(Setmeal::getStatus,1);
        int count = this.count(lqw1);
        if (count>0){
            throw new BussinessException("套餐正在售卖中，无法删除");
        }
        //删除套餐
        this.removeByIds(ids);
        //删除套餐关联关系setmealdish
        LambdaQueryWrapper<SetmealDish> lqw2=new LambdaQueryWrapper<>();
        lqw2.in(SetmealDish::getSetmealId,ids);
        setMealDishService.remove(lqw2);
    }
}
